package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    /*登录功能：
    1.接收前端传输过来的密码，进行md5加密处理
    2.去数据库利用用户名查找用户所对应的密码
    3.如果没有查询到，返回一个用户名或密码错误
    4.对比加密后的password是否一致
    5.对比用户的状态是否是启用状态
    6.登录成功后，将用户的id存入session
    7.返回登录成功
    * */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        //  1.接收前端传输过来的密码，进行md5加密处理
        String password = employee.getPassword();
        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 2.去数据库利用用户名查找用户所对应的密码
        LambdaQueryWrapper<Employee> qwpassword = new LambdaQueryWrapper<>();
        qwpassword.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(qwpassword);
        //3.如果没有查询到，返回一个用户名或密码错误
        if (emp == null) {
            return R.error("登录失败");
        }
        // 4.对比加密后的password是否一致
        if (!emp.getPassword().equals(md5password)) {
            return R.error("登录失败");
        }
        //  5.对比用户的状态是否是启用状态
        if (emp.getStatus() == 0) {
            return R.error("用户被禁用");
        }
        //  6.登录成功后，将用户的id存入session
        request.getSession().setAttribute("employee", emp.getId());
        // 7.返回登录成功
        return R.success(emp);
    }

    // 退出功能
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        //将员工的id从session中移除
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    //新增员工
    @PostMapping
    public R<String> save(@RequestBody Employee employee/* HttpServletRequest request*/) {
        log.info("接收到用户的请求，参数：{}", employee);
        //设置默认用户密码 123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        /*employee.setCreateTime(LocalDateTime.now());//创建时间
        employee.setUpdateTime(LocalDateTime.now());//修改时间
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(employeeId);//创建人
        employee.setUpdateUser(employeeId);//修改人*/
        //保存用户
        employeeService.save(employee);
        return R.success("新增成功");
    }
    //员工条件查询和页面查询
    /*
    * A. 构造分页条件
    B. 构建搜索条件 - name进行模糊匹配
    C. 构建排序条件 - 更新时间倒序排序
    D. 执行查询
    E. 组装结果并返回
    */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("接收到分页查询员工的请求，page:{},pageSize:{},name:{}", page, pageSize, name);
        //分页构建器
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //创建条件查询构建器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //排序,根据修改时间排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    //修改员工账号状态(long类型精度丢失问题，需要配置消息转换器解决)
    @PutMapping
    public R<String> update(@RequestBody Employee employee/*, HttpServletRequest request*/) {
        log.info("接收到前端修改的员工请求：{}", employee);
      /*  Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);//设置修改人
        employee.setUpdateTime(LocalDateTime.now());//设置修改日期*/
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    //修改员工信息
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable long id) {
        log.info("根据id查询：{}", id);
        Employee empid = employeeService.getById(id);
        if (empid != null) {
            return R.success(empid);
        }
        return R.error("未查询到信息");
    }








}